import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../utils/yq_colors.dart';
import 'time_range_display.dart';
import 'package:get/get.dart';

class YQRangeDateTimePicker extends StatefulWidget {
  final DateTime? initialStartDate;
  final DateTime? initialEndDate;
  final Function(DateTime start, DateTime end)? onDateTimeRangeSelected;

  const YQRangeDateTimePicker({
    super.key,
    this.initialStartDate,
    this.initialEndDate,
    this.onDateTimeRangeSelected,
  });

  @override
  State<YQRangeDateTimePicker> createState() => _YQRangeDateTimePickerState();
}

class _YQRangeDateTimePickerState extends State<YQRangeDateTimePicker> {
  DateTime? _startTime;
  DateTime? _endTime;
  int _selectedIndex = 0;
  DateTime? _tempStartTime;
  DateTime? _tempEndTime;

  @override
  void initState() {
    super.initState();
    _startTime = widget.initialStartDate;
    _endTime = widget.initialEndDate;
    _tempStartTime = _startTime;
    _tempEndTime = _endTime;
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => _showDateTimePicker(),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 16),
      
        child: _startTime != null && _endTime != null
            ? TimeRangeDisplay(
                startTime: _startTime!,
                endTime: _endTime!,
              )
            : Text(
                '请选择起始截止时间',
                textAlign: TextAlign.right,
                style: TextStyle(
                  color: Colors.black.withOpacity(0.5),
                  fontSize: 14,
                  
                ),
              ),
      ),
    );
  }

  void _showDateTimePicker() {
    final now = DateTime.now();
    final startDate = widget.initialStartDate != null && widget.initialStartDate!.isAfter(now)
        ? widget.initialStartDate!
        : now;
    final endDate = widget.initialEndDate != null && widget.initialEndDate!.isAfter(startDate)
        ? widget.initialEndDate!
        : startDate.add(const Duration(days: 1));

    // 设置默认值
    _tempStartTime = _startTime ?? startDate;
    _tempEndTime = _endTime ?? endDate;

    showCupertinoModalPopup(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) => Container(
          height: 350,
          color: CupertinoColors.systemBackground,
          child: Column(
            children: [
              CupertinoSegmentedControl<int>(
                padding:const EdgeInsets.symmetric(horizontal: 20,vertical: 10),
                borderColor: Colors.transparent,
              
                children: const {
                  0: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 20),
                    child: Text('起始时间'),
                  ),
                  1: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 20),
                    child: Text('截止时间'),
                  ),
                },
                groupValue: _selectedIndex,
                onValueChanged: (value) {
                  setState(() {
                    _selectedIndex = value;
                  });
                },
              ),
              Container(
                height: 1,
                color: CupertinoColors.systemGrey.withOpacity(0.2),
              ),
              Expanded(
                child: IndexedStack(
                  index: _selectedIndex,
                  children: [
                    _buildDateTimePicker(_tempStartTime ?? startDate, true),
                    _buildDateTimePicker(_tempEndTime ?? endDate, false),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildDateTimePicker(DateTime date, bool isStart) {
    final now = DateTime.now();
    final currentYear = now.year;
    final minYear = currentYear;
    final maxYear = currentYear + 10;
    
    // 计算当前日期在选项中的索引
    final yearIndex = date.year - minYear;
    final monthIndex = date.month - 1;
    final dayIndex = date.day - 1;
    final hourIndex = date.hour;
    
    // 计算当前月份的天数
    final daysInMonth = DateTime(date.year, date.month + 1, 0).day;
    
    return Container(
      height: 216,
      color: CupertinoColors.systemBackground,
      child: Row(
        children: [
          Expanded(
            child: CupertinoPicker(
              itemExtent: 32,
              scrollController: FixedExtentScrollController(
                initialItem: yearIndex,
              ),
              onSelectedItemChanged: (index) {
                final selectedYear = minYear + index;
                final newDate = DateTime(
                  selectedYear,
                  date.month,
                  date.day,
                  date.hour,
                );
                
                if (isStart) {
                  _tempStartTime = newDate;
                  if (_tempEndTime != null && newDate.isAfter(_tempEndTime!)) {
                    _tempEndTime = newDate;
                  }
                } else {
                  _tempEndTime = newDate;
                }
                _updateDateTimeRange();
              },
              children: List.generate(maxYear - minYear + 1, (index) {
                return Center(
                  child: Text(
                    '${minYear + index}年',
                    style: const TextStyle(fontSize: 16),
                  ),
                );
              }),
            ),
          ),
          Expanded(
            child: CupertinoPicker(
              itemExtent: 32,
              scrollController: FixedExtentScrollController(
                initialItem: monthIndex,
              ),
              onSelectedItemChanged: (index) {
                final newDate = DateTime(
                  date.year,
                  index + 1,
                  date.day,
                  date.hour,
                );
                
                if (isStart) {
                  _tempStartTime = newDate;
                  if (_tempEndTime != null && newDate.isAfter(_tempEndTime!)) {
                    _tempEndTime = newDate;
                  }
                } else {
                  _tempEndTime = newDate;
                }
                _updateDateTimeRange();
              },
              children: List.generate(12, (index) {
                return Center(
                  child: Text(
                    '${index + 1}月',
                    style: const TextStyle(fontSize: 16),
                  ),
                );
              }),
            ),
          ),
          Expanded(
            child: CupertinoPicker(
              itemExtent: 32,
              scrollController: FixedExtentScrollController(
                initialItem: dayIndex,
              ),
              onSelectedItemChanged: (index) {
                final newDate = DateTime(
                  date.year,
                  date.month,
                  index + 1,
                  date.hour,
                );
                
                if (isStart) {
                  _tempStartTime = newDate;
                  if (_tempEndTime != null && newDate.isAfter(_tempEndTime!)) {
                    _tempEndTime = newDate;
                  }
                } else {
                  _tempEndTime = newDate;
                }
                _updateDateTimeRange();
              },
              children: List.generate(daysInMonth, (index) {
                return Center(
                  child: Text(
                    '${index + 1}日',
                    style: const TextStyle(fontSize: 16),
                  ),
                );
              }),
            ),
          ),
          Expanded(
            child: CupertinoPicker(
              itemExtent: 32,
              scrollController: FixedExtentScrollController(
                initialItem: hourIndex,
              ),
              onSelectedItemChanged: (index) {
                final newDate = DateTime(
                  date.year,
                  date.month,
                  date.day,
                  index,
                );
                
                if (isStart) {
                  _tempStartTime = newDate;
                  if (_tempEndTime != null && newDate.isAfter(_tempEndTime!)) {
                    _tempEndTime = newDate;
                  }
                } else {
                  _tempEndTime = newDate;
                }
                _updateDateTimeRange();
              },
              children: List.generate(24, (index) {
                return Center(
                  child: Text(
                    '${index.toString().padLeft(2, '0')}:00',
                    style: const TextStyle(fontSize: 16),
                  ),
                );
              }),
            ),
          ),
        ],
      ),
    );
  }

  void _updateDateTimeRange() {
    if (widget.onDateTimeRangeSelected != null && _tempStartTime != null && _tempEndTime != null) {
      widget.onDateTimeRangeSelected!(_tempStartTime!, _tempEndTime!);
      setState(() {
        _startTime = _tempStartTime;
        _endTime = _tempEndTime;
      });
    }
  }
} 